<template>
  <el-container>
    <!-- 顶部查询栏 -->
    <el-header style="margin-top: 20px;width:20%;margin-left: 41%;">
      <el-input v-model="queryParams.name" placeholder="输入商品名称进行模糊查询" @input="handleSearch" clearable>
        <template #append>
          <el-button style="background-color: #30d104;color: white;" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </el-header>

    <!-- 筛选条件按钮 -->
    <el-main style="margin-left: 25%; margin-top: -2%;">
      <div class="filter-section">
        <!-- 分类筛选 -->
        <div class="filter-row">
          <span class="filter-label">分&nbsp&nbsp&nbsp&nbsp类</span>
          <el-button-group>
            <el-button
                v-for="category in categories"
                :key="category.id"
                :type="queryParams.categoryId === category.id ? 'primary' : 'default'"
                @click="queryParams.categoryId = category.id"
            >{{ category.name }}</el-button>
          </el-button-group>
        </div>

        <!-- 价格筛选 -->
        <div class="filter-row">
          <span class="filter-label">价&nbsp&nbsp&nbsp&nbsp格</span>
          <el-button-group>
            <el-button
                v-for="price in priceRanges"
                :key="price.value"
                :type="queryParams.price === price.value ? 'primary' : 'default'"
                @click="queryParams.price = price.value"
            >{{ price.label }}</el-button>
          </el-button-group>
        </div>

        <!-- 完整率筛选 -->
        <div class="filter-row">
          <span class="filter-label">完整率</span>
          <el-button-group>
            <el-button
                v-for="rate in brokenRateOptions"
                :key="rate.value"
                :type="queryParams.brokenRate === rate.value ? 'primary' : 'default'"
                @click="queryParams.brokenRate = rate.value"
            >{{ rate.label }}</el-button>
          </el-button-group>
        </div>
      </div>
    </el-main>

    <!-- 商品展示 -->
    <el-row :gutter="20" style="width: 90%;margin-left: 6%;">
      <el-col :span="6" v-for="(product, index) in products" :key="index">
        <el-card style="margin-top: 20px;">
          <!-- Conditionally display '我的' label if the product belongs to the current user -->
          <template v-if="product.userId === currentUserId">
            <el-tag type="success" style="position: relative; top: 10px; right: 10px;">我的</el-tag>
          </template>
          <template v-else>
            <el-tag type="info" style="position: relative; top: 10px; right: 10px;">他人</el-tag>
          </template>
          <img
              :src="product.image || defaultImage"
              class="product-image"
              alt="商品图片"
              @click="goToDetailPage(product.id)"
          />
          <div style="padding: 14px;">
            <h3>{{ product.name }}</h3>
            <p><span style="color: red;">￥</span><span style="color: red;font-size: 24px;">{{ product.price }}</span></p>
            <p>重量: {{ product.weight }}g</p>
            <p>积分: {{ product.point }}</p>
            <p>完整率: {{ product.brokenRate * 100 }}%</p>
            <p>库存: {{ product.nums }}</p>
            <p class="price-text">{{ product.description }}</p>
          </div>
          <el-button style="margin-left: 6%" type="primary" @click="handleExchange(product)">我要购买/交换</el-button>
          <el-button @click="handleAddToCart(product)">加入购物车</el-button>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout=" prev, pager, next"
        :total="totalItems"
        @current-change="handlePageChange"
        style="margin-left: 27%;margin-top: 20px;"
    >
    </el-pagination>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getGoodsListAPI, getCategoryListAPI } from '@/api/Goods.js';
import router from "@/router/index.js";
import { useUserStore } from '@/stores/user.js'; // Adjust based on your actual store path

// Access user ID from the store
const store = useUserStore();
const currentUserId = store.UserId; // Get current user's userId

const queryParams = ref({
  pageNum: 1,
  pageSize: 12,
  name: '',
  categoryId: null,
  price: null,  // Maximum price
  brokenRate: null,
  type:2,
});

const categories = ref([
  { name: '全部', id: null }, // Add "全部" (All) option
]);

// Fetch category list
const getCategoryList = async () => {
  try {
    const response = await getCategoryListAPI(2);
    if (response.data.code === 200) {
      categories.value = [{ name: '全部', id: null }, ...response.data.data];  // Add "全部" option and update category list
    } else {
      Error('获取分类失败：' + response.data.msg);
    }
  } catch (error) {
    Error('获取分类失败：' + error.message);

  }
};

const priceRanges = ref([
  { label: '全部', value: null }, // Add "全部" (All) option
  { label: '10元以下', value: 10 },
  { label: '50元以下', value: 50 },
  { label: '100元以下', value: 100 },
  { label: '200元以下', value: 200 },
  { label: '500元以下', value: 500 },
  { label: '501元以上', value: 501 },
]);

const brokenRateOptions = ref([
  { label: '全部', value: null },  // Add "全部" (All) option
  { label: '大于9成', value: 0.9 },
  { label: '大于8成', value: 0.8 },
  { label: '大于7成', value: 0.7 },
  { label: '大于6成', value: 0.6 },
  { label: '大于5成', value: 0.5 },
  { label: '大于4成', value: 0.4 },
  { label: '大于3成', value: 0.3 },
]);

const products = ref([]);
const totalItems = ref(0);  // Total product count from the backend
const defaultImage = 'https://via.placeholder.com/150';  // Default product image

// Search for products
const handleSearch = async () => {
  try {
    const response = await getGoodsListAPI(queryParams.value);
    if (response.data.code === 200) {
      products.value = response.data.data.rows;  // Update product list
      totalItems.value = response.data.data.total;  // Update total items count
    } else {
      console.error('查询商品失败:', response.msg);
    }
  } catch (error) {
    console.error('查询商品失败:', error);
  }
};

const goToDetailPage = (productId) => {
  router.push({
    path: '/product',
    query: { productId }
  });
};

// Handle product exchange
const handleExchange = (product) => {
  console.log('交换商品:', product.name);
};

// Add to cart
const handleAddToCart = (product) => {
  console.log('加入购物车:', product.name);
};

// Handle page change
const handlePageChange = (newPage) => {
  queryParams.value.pageNum = newPage;
  handleSearch();  // Re-query product list
};

// On component mount, fetch categories and initial product list
onMounted(() => {
  getCategoryList();  // Load category list
  handleSearch();  // Load initial product list
});
</script>

<style scoped>
.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-row {
  margin-bottom: 10px;
}

.filter-label {
  display: inline-block;
  width: 50px;
  font-weight: bold;
  margin-right: 10px;
}

.price-text {
  white-space: nowrap;   /* No line break */
  overflow: hidden;      /* Hide overflow */
  text-overflow: ellipsis; /* Display ellipsis */
  font-size: 12px;
  color: #666;
}

.el-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}
</style>
